#include "my_stdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


const int basesize = 1024;
mFILE* mfopen(const char* filename,const char* mode)
{
    mFILE * pf = (mFILE*)malloc(sizeof(mFILE));
    if (pf == NULL) return NULL;
    if (strcmp(mode,"w") == 0)
    {
        int fd = open(filename,O_WRONLY | O_CREAT | O_TRUNC,0666);
        if (fd < 0) return NULL;
        pf->fileno = fd;
    }   
    else if(strcmp(mode,"r") == 0)
    {
        int fd = open(filename,O_RDONLY);
        if (fd < 0) return NULL;
        pf->fileno = fd;
    }
    else if(strcmp(mode,"a") == 0)
    {
        int fd = open(filename,O_TRUNC | O_CREAT | O_APPEND,0666);
        if (fd < 0) return NULL;
        pf->fileno = fd;
    }
    pf->flg = FFLUSHLINE;
    pf->size = 0;
    pf->cap = SIZE;
    return pf;
}
int mfwrite(void* Outputbuffer,int num,mFILE* pf)
{
    //假设之间已经打开了
   memcpy(pf->buffer+pf->size,Outputbuffer,num);
    pf->size += num;
    if (pf->flg == FFLUSHLINE && pf->size > 0 && pf->buffer[pf->size-1] =='\n')
        mfflush(pf);
   return num; 
}
void mfflush(mFILE* pf)
{  
   write(pf->fileno,pf->buffer,pf->size);
    pf->size = 0;
}
int mfclose(mFILE* pf)
{
    if (pf->size > 0)
    {
        mfflush(pf);
    }
    int ret = close(pf->fileno);
    return ret;
}
